<?php

class ServicesController extends \BaseController {

    /**
     * Display a listing of the resource.
     * GET /services
     *
     * @return Response
     */
    public function index()
    {
        //
        $pub = Pub::find(1);

        $PATH = $pub->path;

        $customer_id = Session::get('customer_id');
        $type = Input::get('type');
        if($type == 'final'){
            $services = Service::where('customer_id',$customer_id)->where('state',3)->orderBy('created_at', 'DESC')->get();
        }else{
            $services = Service::where('customer_id',$customer_id)->where('state','<',3)->orderBy('created_at', 'DESC')->get();
        }
        return View::make('services.index',compact('services','PATH','type'));
    }


    public function orders(){
        $customer_id = Session::get('customer_id');
        $services = Service::where('customer_id',$customer_id)->where('type',20)->get();
        return View::make('services.index',compact('services'));
    }
    /**
     * Show the form for creating a new resource.
     * GET /services/create
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     * POST /services
     *
     * @return Response
     */
    public function store()
    {
        //

        $customer_id = Session::get('customer_id');
        $customer = Customer::find($customer_id);
        $id = Input::get('id');
        $service = Service::find($id);
        if(Input::get('type') == 'rate'){
            if($service->rate_id > 0){
                $notice = '请勿重复评价！';
                return View::make('errors.error',compact('notice'));
                exit;
            }


            $rate = new Rate();
            $rate->form1 = Input::get('rate1');
            $rate->form2 = Input::get('rate2');
            $rate->form3 = Input::get('rate3');
            $rate->remark = Input::get('textfield');
            $rate->area = $service->section_id;
            $rate->xiaoqu = $service->mount->area_id;
            $rate->city = $customer->city;
            $rate->service_id = $id;
            $rate->machine_id = $service->mount->machine_id;
            $rate->customer_id = $customer_id;
            $rate->work_id = $service->worker_id;
            $rate->save();



            Customer::add_points($customer_id,'rate',1,$service->id);//增加积分
            $service->rate_id = $rate->id;
            $service->save();
        }else{
            $comment = new Comment();

            if($service->worker_id == $customer_id){
                $comment->work_id = $customer_id;
            }else{
                $comment->customer_id = $customer_id;
            }

            $content = Input::get('textfield');
            $comment->remark = $content;
            $comment->service_id = $id;
            $comment->save();
        }

        return Redirect::route('services.show',$id);
    }

    /**
     * Display the specified resource.
     * GET /services/{id}
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
        $biaozhuns = $this->biaozhun_detail();



        $customer_id = Session::get('customer_id');
        $customer = Customer::find($customer_id);
        $service = Service::find($id);
        $code = Input::get('code');
        $worker = 0;
        if($service->worker_id == $customer_id){
            $worker = 1;
        }

        $section = User::where('area',$customer->area)->where('permissions','{"section":1}')->first();
        $big = User::find(14);
        $mount = Mount::find($service->mount_id);
        $name = array('filterone','filtertwo','filterthree','filterfour','filterfive','filtersix','filterseven','filtereight','filternine','filterten');
        for($i = 0;$i < $mount->machine->count ;$i++){
            $filters[] = $name[$i];
        }

        if($service->biaozhun){
            $detail = unserialize($service->biaozhun);
        }
        if($service->state == 1){
            return View::make('services.show',compact('service','code','worker','filters','mount','section','big'));
        }elseif($service->state == 2){
            return View::make('services.show2',compact('service','code','worker','filters','mount','section','big'));
        }elseif($service->state == 3  && $service->rate_id == 0){
            return View::make('services.show3',compact('service','code','worker','filters','mount','biaozhuns','detail','section','big'));
        }else{

            return View::make('services.showok',compact('service','code','worker','filters','mount','biaozhuns','detail','section','big'));
        }
    }

    /**
     * Show the form for editing the specified resource.
     * GET /services/{id}/edit
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        //

        $biaozhuns = $this->biaozhun();
        $machines = Machine::all();
        $customer_id = Session::get('customer_id');
        $service = Service::find($id);
        $code = Input::get('code');

        if(isset($code)){
            $code_count = Mount::where('code',$code)->count();
            if($code_count > 0){
                $notice = '该机器二维码已被使用！';
                return View::make('errors.error',compact('notice'));
            }
        }


        if($service->worker_id != $customer_id){
            echo '不是你的工单';
            exit;
        }
        return View::make('services.edit',compact('service','code','machines','biaozhuns'));
    }

    /**
     * Update the specified resource in storage.
     * PUT /services/{id}
     *
     * @param  int  $id
     * @return Response
     */
    public function update($id)
    {
        //

        $time = time();
        DB::beginTransaction();

        $service  = Service::find($id);
        $mount = Mount::find($service->mount_id);
        $machine = Machine::find(Input::get('machine_id'));
        $EventKey = Input::get('code');
        if($mount->state == 0 && $service->state == 2){
            $mount->state = 1;

//            $code = Code::where('start','<=',$EventKey)
//                ->where('stop','>=',$EventKey)
//                ->firstOrFail();


//            $mount->machine_id = $code->machine_id;
            $mount->shiyong_start = time();
            $mount->code = $EventKey;

            $xiaoqu = Area::find($mount->area_id);
            $xiaoqu->mount_count = $xiaoqu->mount+1;
            $xiaoqu->save();

            $work = Work::find($service->worker_id);
            $work->count = $work->count+1;
            $work->save();

            for($i = 1; $i<= $machine->count;$i++){
                $cname = 'filter'.$i;
                $data[] = array('mount_id'=>$mount->id,'commodity_id'=>$machine->$cname,'start_time'=>$time,'state'=>1);
            }

            DB::table('filterins')->insert($data);
            $customer = Customer::find($mount->customer_id);
            if($customer->type == 0){
                $customer->type = 1;
            }
            $customer->service_time = $customer->service_time+6;

            $customer->save();


            Customer::add_points($customer->id,'attempt_finish',1,$mount->id);//增加积分
            if($customer->invite_id > 0){//是否有邀请人
                Customer::add_points($customer->invite_id,'inviter_attempt_finish',1,$mount->id,$customer->id);//增加积分
            }



        }elseif($mount->state == 2  && $service->state == 2 && $service->type == 10){//机器状态正确 && 工单状态正确 && 类型为订购

            //1:转发软文，2：填写信息3：试用机器4：评价5:试用成功 邀请人加分6：购买机器7：购买机器邀请人加分


            $customer = Customer::find($mount->customer_id);
            Customer::add_points($mount->customer_id,'pay_finish',1,$mount->id);//增加积分
            if($customer->invite_id > 0){//是否有邀请人
                Customer::add_points($customer->invite_id,'inviter_pay_finish',1,$mount->id,$customer->id);//增加积分
            }


            $mount->state = 3;
        }elseif($mount->state == 4  && $service->state == 2 && $service->type == 11){
            $mount->code = '';
            $mount->state = 5;
        }elseif($service->state == 2){
            $mount->state = 6;
        }


        $mount->from = Input::get('from');
        $mount->save();
        if($service->type == 13   && $service->state == 2){
            $filterin = Filterin::find($service->filters);
            $filterin->start_time = time();
            $filterin->save();
        }


        $biaozhuns = $this->biaozhun();

        foreach(Input::get('biaozhun') as $biaozhun){
            $arr = explode('_',$biaozhun);
            $biaozhuns[$arr[0]]['lists'][$arr[1]]['sel'][$arr[2]] = 1;
        }
        if(Input::get('0_0_0')){
            $biaozhuns[0]['lists'][0]['sel'][0] = Input::get('0_0_0');
        }
        if(Input::get('2_0_0')){
            $biaozhuns[2]['lists'][0]['sel'][0] = Input::get('2_0_0');
        }
        if(Input::get('5_0_0')){
            $biaozhuns[5]['lists'][0]['sel'][0] = Input::get('5_0_0');
        }
        if(Input::get('5_1_0')){
            $biaozhuns[5]['lists'][1]['sel'][0] = Input::get('5_1_0');
        }

        $biao = serialize($biaozhuns);

        $service->biaozhun = $biao;

        $service->state   = 3;
        $service->save();

        DB::commit();

        $this->forcustomer($service);
        return View::make('mounts.success');

    }

    /**
     * Remove the specified resource from storage.
     * DELETE /services/{id}
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        //
    }


    public function paidan(){
        $id = Input::get('id');
        $service = Service::find($id);
        $works = Work::where('section_id',$service->section_id)->orderBy('created_at', 'DESC')->get();
        return View::make('services.paidan',compact('service','works'));
    }

    public function paidan_store(){

        DB::beginTransaction();
        Service::paidan(Input::get('service_id'),Input::get('radio'));
        $work = Work::find(Input::get('radio'));
        $service = Service::find(Input::get('service_id'));

        $this->forcustomers($service,$work);
        $this->forworker($service,$work);

        DB::commit();
        return Redirect::route('services.paidan',array('id'=>$service->id));
    }




    public function forworker($service,$work){

        $data[0] = '尊敬的'.$work->name.'您有一条新的工单需要处理';

        $type[1] = '试用';
        $type[10] = '订购';
        $type[11] = '拆机';
        $type[12] = '维修';
        $type[13] = '换芯';


        $data[1] = $type[$service->type];
        $data[2] = $service->mount->machine->name;
        $data[3]= $work->name;
        $data[4]= '网点';
        $data[5]= $work->mobile;
        $data[6]= '点击查看工单详细信息';
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc64f995bebe39161&redirect_uri=http%3a%2f%2fcrm.leaderphos.com%2fdiscern&response_type=code&scope=snsapi_userinfo&state=service_'.$service->id.'#wechat_redirect';
        Template::newone($work->openid,$data,$url,1);
    }
    public function forcustomers($service,$work){

        $data[0] = '尊敬的客户您有一条工单已派单';

        $type[1] = '试用';
        $type[10] = '订购';
        $type[11] = '拆机';
        $type[12] = '维修';
        $type[13] = '换芯';


        $data[1] = $type[$service->type];
        $data[2] = $service->mount->machine->name;
        $data[3]= $work->name;
        $data[4]= '网点';
        $data[5]= $work->mobile;
        $data[6]= '点击查看详细信息';
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc64f995bebe39161&redirect_uri=http%3a%2f%2fcrm.leaderphos.com%2fdiscern&response_type=code&scope=snsapi_userinfo&state=service#wechat_redirect';
        Template::newone($service->customer->openid,$data,$url,1);
    }

    public function forcustomer($service){

        $data[0] = '尊敬的客户您有一条工单已完成';

        $data[1] = '已完成';
        $data[2] = date('Y-m-d H:i:s');
        $data[3]= '请您点击连接对此次服务进行评价';
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc64f995bebe39161&redirect_uri=http%3a%2f%2fcrm.leaderphos.com%2fdiscern&response_type=code&scope=snsapi_userinfo&state=rates_'.$service->id.'#wechat_redirect';

        \Template::newone($service->customer->openid,$data,$url,2);
    }

    public function biaozhun(){

        $biaozhuns = array(
            array(
                'name' => '水质监测',
                'lists' => array(
                    array(
                        'name'=>'TDS值测试',
                        'sel'=>array('txt')
                    )
                )
            ),
            array(
                'name' => '清洗/更换滤芯',
                'lists' => array(
                    array(
                        'name'=>'PP棉及滤筒',
                        'sel'=>array('清洗完成','更换完成')
                    ),
                    array(
                        'name'=>'UDF及滤筒',
                        'sel'=>array('清洗完成','更换完成')
                    ),
                    array(
                        'name'=>'CTO及滤筒',
                        'sel'=>array('清洗完成','更换完成')
                    ),
                    array(
                        'name'=>'UF及滤筒',
                        'sel'=>array('清洗完成','更换完成')
                    ),
                    array(
                        'name'=>'RO膜及滤筒',
                        'sel'=>array('清洗完成','更换完成')
                    ),
                    array(
                        'name'=>'T33',
                        'sel'=>array('更换完成')
                    ),
                    array(
                        'name'=>'多功能滤芯',
                        'sel'=>array('更换完成')
                    )
                )
            ),
            array(
                'name' => '机器维修',
                'lists' => array(
                    array(
                        'name'=>'部件更换明细',
                        'sel'=>array('txt')
                    )
                )
            ),
            array(
                'name' => '注意事项提醒',
                'lists' => array(
                    array(
                        'name'=>'机器正常状态提醒',
                        'sel'=>array('告知完成')
                    ),
                    array(
                        'name'=>'机器异常状态提醒',
                        'sel'=>array('告知完成')
                    ),
                    array(
                        'name'=>'清洁卫生',
                        'sel'=>array('清洁完成')
                    )
                )
            ),
            array(
                'name' => '机器保养',
                'lists' => array(

                    array(
                        'name'=>'管路检查',
                        'sel'=>array('告知完成')
                    ),
                    array(
                        'name'=>'电路检查',
                        'sel'=>array('告知完成')
                    ),
                    array(
                        'name'=>'隐患检查',
                        'sel'=>array('告知完成')
                    ),
                )
            ),
            array(
                'name' => '上门服务',
                'lists' => array(
                    array(
                        'name'=>'上门费用',
                        'sel'=>array('txt')
                    ),
                    array(
                        'name'=>'服务费用',
                        'sel'=>array('txt')
                    )
                )
            ),
        );
        return $biaozhuns;
    }
    public function biaozhun_detail(){

        $biaozhuns = array(
            array(
                'name' => '水质监测',
                'lists' => array(
                    array(
                        'name'=>'TDS值测试',
                        'sel'=>array('txt'),
                        'detail'=>'1、常规测试时打开纯水龙头5秒后接水，用TDS笔测试。<br />2、新装产品在压力桶前管子口处接水，用TDS笔测试。<br />3、TDS值≤30为正常值。'
                    )
                )
            ),
            array(
                'name' => '清洗/更换滤芯',
                'lists' => array(
                    array(
                        'name'=>'PP棉及滤筒',
                        'sel'=>array('清洗完成','更换完成'),
                        'detail'=>'1、冲洗PP滤芯表面泥沙铁锈，直至冲洗出来的水清澈。<br /> 2 、PP滤芯内侧中圈变黄变黑时则需要更换。<br /> 3 、滤筒使用干净抹布擦拭冲洗，直至内外侧看不到污垢。<br />'
                    ),
                    array(
                        'name'=>'UDF及滤筒',
                        'sel'=>array('清洗完成','更换完成'),
                        'detail'=>'1、冲洗UDF滤芯表面杂质，直至冲洗出来的水清澈。   <br />    2 、发现UDF滤芯有异味则需要更换，正常一年更换。   <br />                  3 、滤筒使用干净抹布擦拭冲洗，直至内外侧看不到污垢。'
                    ),
                    array(
                        'name'=>'CTO及滤筒',
                        'sel'=>array('清洗完成','更换完成'),
                        'detail'=>'1、冲洗CTO滤芯表面杂质，直至冲洗出来的水清澈。   <br />    2 、发现CTO滤芯有异味则需要更换，正常一年更换。     <br />                3 、滤筒使用干净抹布擦拭冲洗，直至内外侧看不到污垢。'
                    ),
                    array(
                        'name'=>'UF及滤筒',
                        'sel'=>array('清洗完成','更换完成'),
                        'detail'=>'1、冲洗UF滤芯表面杂质，直至冲洗出来的水清澈。   <br />       2 、发现UF滤芯堵塞不出水则需要更换，正常两年更换。      <br />               3 、滤筒使用干净抹布擦拭冲洗，直至内外侧看不到污垢。'
                    ),
                    array(
                        'name'=>'RO膜及滤筒',
                        'sel'=>array('清洗完成','更换完成'),
                        'detail'=>'1、冲洗RO膜滤芯表面杂质，直至冲洗出来的水清澈。  <br />     2 、发现RO膜滤芯堵塞不出水或TDS值不达标则需要更换。正常两年更换。<br />3 、滤筒使用干净抹布擦拭冲洗，直至内外侧看不到污垢。'
                    ),
                    array(
                        'name'=>'T33',
                        'sel'=>array('更换完成'),
                        'detail'=>'1、正常一年整体更换。<br /> 2、发现纯水有异味，口感不佳，则需要更换。'
                    ),
                    array(
                        'name'=>'多功能滤芯',
                        'sel'=>array('更换完成'),
                        'detail'=>'1、正常一年整体更换。<br /> 2、发现PH值达不到弱碱性则需要更换。'
                    )
                )
            ),
            array(
                'name' => '机器维修',
                'lists' => array(
                    array(
                        'name'=>'部件更换明细',
                        'sel'=>array('txt'),
                        'detail'=>'需将旧部件给客户展示。'
                    )
                )
            ),
            array(
                'name' => '注意事项提醒',
                'lists' => array(
                    array(
                        'name'=>'机器正常状态提醒',
                        'sel'=>array('告知完成'),
                        'detail'=>'1、机器在自来水停水的情况下会自动报警，需要把电源关闭，通水了重新通电，机器自动正常工作。    <br />           2、更换T33滤芯之后，需要对T33滤芯进行冲洗，2-3桶水，刚开始会有黑水，属于正常现象。              <br />         3、长时间不在家，需要把机器的水源电源切断。      <br />     4、机器正常工作时会有泵工作的声音，制水结束机器停止工作，就没有声音。      <br />      5、机器在工作状态下会排放废水，停止工作后不产生废水。'
                    ),
                    array(
                        'name'=>'机器异常状态提醒',
                        'sel'=>array('告知完成'),
                        'detail'=>'1、机器工作不正常，报检修，需要切断电源水源，联系服务人员上门维护。<br /> 2、机器发现渗水漏水，需要切断电源水源，联系服务人员上门维护。'
                    ),
                    array(
                        'name'=>'清洁卫生',
                        'sel'=>array('清洁完成'),
                        'detail'=>'恢复客户家原先布置，清洁橱柜、地面、擦干水渍。'
                    )
                )
            ),
            array(
                'name' => '机器保养',
                'lists' => array(

                    array(
                        'name'=>'管路检查',
                        'sel'=>array('告知完成'),
                        'detail'=>'1、管路是否松动。<br />2、橡皮垫片是否点好。<br /> 3、废水管固定是否安全。<br />4、水龙头是否松动。<br />5、发现问题重新处理好。'
                    ),
                    array(
                        'name'=>'电路检查',
                        'sel'=>array('告知完成'),
                        'detail'=>'1、检查插排是否安全，是否会被台面漏水滴到。     <br />      2、检查机器是否会北台面漏水滴到。'
                    ),
                    array(
                        'name'=>'隐患检查',
                        'sel'=>array('告知完成'),
                        'detail'=>'1、机器接电是否老化。<br />2、机器废水排放是否通畅。<br />  3、客户家水管是否有老化，渗水现象，建议更换。      <br />             4、客户家下水管是否有隐患，容易溢水，或产生异味。'
                    ),
                )
            ),
            array(
                'name' => '上门服务',
                'lists' => array(
                    array(
                        'name'=>'上门费用',
                        'sel'=>array('txt'),
                        'detail'=>'各个城市的距离及人工成本会有差异。'
                    ),
                    array(
                        'name'=>'服务费用',
                        'sel'=>array('txt'),
                        'detail'=>'各个城市的距离及人工成本会有差异。'
                    )
                )
            )
        );
        return $biaozhuns;
    }

}